package com.ruoyi.aitcommon.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aitcommon.anotation.ApiLog;
import com.ruoyi.aitcommon.config.ConfigManager;
import com.ruoyi.aitcommon.utils.*;
import com.ruoyi.aitcommon.vo.RestCallVO;
import com.ruoyi.aitcommon.vo.RuntimeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/aitcommon/runtime")
public class AITRunTimeController {
    @Autowired
    RuntimeManager runtimeManager;

    @ApiLog("REST调用")
    @GetMapping("/restCallRun")
    public JSONObject restCallRun(RestCallVO restCall){
        String retstr="";
        try{
            if(restCall.getMethod().equals("POST")){
                retstr= RestServiceUtils.post(restCall.getUrl(),restCall.getHeadMap(), restCall.getBody());
            }else if(restCall.getMethod().equals("GET")){
                retstr=RestServiceUtils.get(restCall.getUrl(),restCall.getHeadMap(),null);
            }

//            格式化返回值
            if(JSONUtils.validJSONObjectStr(retstr)){
                final JSONObject json = JSONObject.parseObject(retstr);
                if(ObjUtils.isNotBlank(json)){
                    restCall.setResponse(JSONObject.toJSONString(json,true));
                }
            }else{
                restCall.setResponse(retstr);
            }

            return JSONResult.success(restCall);
        }catch (Exception ex){
            return JSONResult.error(ex.getMessage());
        }
    }

    @ApiLog("加载运行信息")
    @GetMapping("/loadInfo")
    public JSONObject loadInfo(String flowCode) {
        JSONObject retjosn=new JSONObject();
        try{
            if(StrUtil.isBlank(flowCode))
                throw new Exception("传入flowCode为空");
            final RuntimeVO runInfo = runtimeManager.getRunInfo(flowCode);
            final String runLog = runtimeManager.getRunLog(flowCode);
            if(runInfo!=null) {
                retjosn=(JSONObject) JSONObject.toJSON(runInfo);
                retjosn.put("runLog",runLog);
            }
            return JSONResult.success(retjosn);
        }catch (Exception ex){
            return JSONResult.error(ex.getMessage());
        }
    }

    @ApiLog("加载运行信息")
    @GetMapping("/loadSQLInfo")
    public JSONObject loadSQLInfo(String flowCode) {
        JSONObject retjosn=new JSONObject();
        try{
            if(StrUtil.isBlank(flowCode))
                throw new Exception("传入flowCode为空");
            final RuntimeVO runInfo = runtimeManager.getRunInfo(flowCode);
            final List<String> sqlInfo = runtimeManager.getSQLInfo(flowCode);
            if(runInfo!=null) {
                retjosn=(JSONObject) JSONObject.toJSON(runInfo);
                if(ObjUtils.isNotBlank(sqlInfo)){
                    StringBuilder sqlb=new StringBuilder();
                    sqlb.append("-- 注意:SQL日志只记录前10条\r\n");
                    sqlb.append("\r\n");

                    int i=0;
                    for(String sql:sqlInfo){
                        i++;
                        String msg="-- 第[%s]条:\r\n";
                        msg=String.format(msg,i);
                        sqlb.append(msg);
                        sqlb.append(sql);
                        sqlb.append("\r\n");
                    }
                    retjosn.put("sqlInfo",sqlb.toString());
                }
            }
            return JSONResult.success(retjosn);
        }catch (Exception ex){
            return JSONResult.error(ex.getMessage());
        }
    }

    @ApiLog("加载REST调用信息")
    @GetMapping("/loadCallInfo")
    public JSONObject loadCallInfo(String flowCode) {
        JSONObject retjosn=new JSONObject();
        try{
            if(StrUtil.isBlank(flowCode))
                throw new Exception("传入flowCode为空");
            final RuntimeVO runInfo = runtimeManager.getRunInfo(flowCode);
            final List<Map<String, Object>> restCall = runtimeManager.getRestCall(flowCode);
            if(runInfo!=null) {
                retjosn=(JSONObject) JSONObject.toJSON(runInfo);
                if(ObjUtils.isNotBlank(restCall)){
//                    增加扩展信息restCall
                    List<RestCallVO> retlist=new ArrayList<>();
                    for(Map<String,Object> callmap:restCall){
                        RestCallVO callvo=JSONObject.toJavaObject(new JSONObject(callmap),RestCallVO.class);

//                            json格式化处理
                        final Object bodystr = callvo.getBody();
                        if(JSONUtils.validJSONObjectStr(bodystr.toString())){
                            final Object json = JSONObject.parse(bodystr.toString());
                            if(ObjUtils.isNotBlank(json)){
                                String ret=JSONObject.toJSONString(json, true);
                                callvo.setBody(ret);
                            }
                        }
                        final Object response = callvo.getResponse();
                        if(JSONUtils.validJSONObjectStr(response.toString())){
                            final Object json = JSONObject.parse(response.toString());
                            if(ObjUtils.isNotBlank(json)){
                                String ret=JSONObject.toJSONString(json, true);
                                callvo.setResponse(ret);
                            }
                        }
                        retlist.add(callvo);
                    }
                    retjosn.put("restCall",retlist);
                }
            }
            return JSONResult.success(retjosn);
        }catch (Exception ex){
            return JSONResult.error(ex.getMessage());
        }
    }
}
